import requests
import base64
import json

class SilicanAPI:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "https://api.siliconflow.cn/v1"  
    
    def analyze_image(self, image_path, prompt):
        """调用硅基流动API分析图像"""
    # 读取并编码图像
        with open(image_path, "rb") as image_file:
            encoded_image = base64.b64encode(image_file.read()).decode('utf-8')
    
    # 构建请求
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
    
   
        payload = {
            "model": "Qwen/Qwen2.5-VL-72B-Instruct",  
            "messages": [
                {
                    "role": "user",
                    "content": [
                
                        {"type": "image_url", 
                        "image_url": {"url": f"data:image/jpeg;base64,{encoded_image}"}},
                        {"type": "text", "text": prompt}
                    ]
                }
            ],
            "max_tokens": 1000
    }
    
        try:
            response = requests.post(
                f"{self.base_url}/chat/completions", 
                headers=headers, 
                json=payload
        )
            response.raise_for_status()  # 触发HTTP错误
            return response.json()["choices"][0]["message"]["content"]
        except requests.exceptions.HTTPError as e:
            # 打印详细错误信息以便调试
            return f"API错误 {response.status_code}: {response.text}"
        except Exception as e:
            return f"调用失败: {str(e)}"
    
    def detect_crop_health(self, image_path):
        """检测农作物健康状态"""
        # 获取图像描述
        description_prompt = "请详细描述这张图片中的农作物状况，包括作物类型、叶片颜色、是否有斑点或异常区域。"
        description = self.analyze_image(image_path, description_prompt)
        
        # 判断健康状况
        health_prompt = "根据图像内容，判断这些农作物是否健康。如果发现疾病或害虫，请指出可能的问题。请以'健康状态:'开头回答，并给出置信度(0-1)。"
        health_judgment = self.analyze_image(image_path, health_prompt)
        
        # 提取健康状态和置信度
        health_status = "未知"
        confidence = 0.5
        
        if "健康状态:" in health_judgment:
            parts = health_judgment.split("健康状态:")[1].strip().split("\n")[0]
            if "健康" in parts:
                health_status = "健康"
            elif "不健康" in parts or "病" in parts or "害虫" in parts:
                health_status = "不健康"
            
            # 尝试提取置信度
            import re
            confidence_match = re.search(r"置信度?[：:]?\s*([0-9.]+)", health_judgment)
            if confidence_match:
                confidence = float(confidence_match.group(1))
        
        # 获取建议
        suggestion_prompt = "为这张图片中的农作物提供防治建议和管理措施。"
        suggestions = self.analyze_image(image_path, suggestion_prompt)
        
        # 尝试识别作物类型
        crop_type = "未知作物"
        if "水稻" in description:
            crop_type = "水稻"
        elif "玉米" in description:
            crop_type = "玉米"
        elif "小麦" in description:
            crop_type = "小麦"
        elif "番茄" in description:
            crop_type = "番茄"
        elif "黄瓜" in description:
            crop_type = "黄瓜"
        elif "大豆" in description:
            crop_type = "大豆"
        elif "花生" in description:
            crop_type = "花生"
        elif "油菜" in description:
            crop_type = "油菜"
        elif "土豆" in description:
            crop_type = "土豆"
        elif "茄子" in description:
            crop_type = "茄子"
        elif "辣椒" in description:
            crop_type = "辣椒"
        elif "南瓜" in description:
            crop_type = "南瓜"
        elif "红薯" in description:
            crop_type = "红薯"
        elif "草莓" in description:
            crop_type = "草莓"
        elif "香蕉" in description:
            crop_type = "香蕉"
        elif "葡萄" in description:
            crop_type = "葡萄"
        elif "柑橘" in description:
            crop_type = "柑橘"
        elif "梨" in description:
            crop_type = "梨"
        elif "苹果" in description:
            crop_type = "苹果"
        elif "桃" in description:
            crop_type = "桃"
        elif "杏" in description:
            crop_type = "杏"
        elif "枣" in description:
            crop_type = "枣"
        elif "石榴" in description:
            crop_type = "石榴"
        elif "西瓜" in description:
            crop_type = "西瓜"

        

    
        
        return {
            "crop_type": crop_type,
            "health_status": health_status,
            "confidence": confidence,
            "description": description,
            "suggestions": suggestions
        }
    def agricultural_qa(self, question):
        """农业知识问答"""
        prompt = f"""你是一名农业专家，请用中文回答以下农业相关问题。回答要详细、实用，适合农民朋友理解，非农业相关的问题请拒绝回答。

    问题：{question}

    请提供专业、准确的农业知识解答："""
    
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
    
        payload = {
            "model": "Qwen/Qwen2.5-72B-Instruct", 
            "messages": [
                {
                    "role": "user",
                    "content": prompt
                }
            ],
            "max_tokens": 2000,
            "temperature": 0.7
        }
    
        try:
            response = requests.post(
                f"{self.base_url}/chat/completions", 
                headers=headers, 
                json=payload,
                timeout=60  # 添加超时设置
            )
            response.raise_for_status()
            result = response.json()
            return result["choices"][0]["message"]["content"]
        except requests.exceptions.RequestException as e:
            return f"网络请求失败: {str(e)}"
        except KeyError as e:
            return f"解析API响应失败: {str(e)}，响应内容: {response.text}"
        except Exception as e:
            return f"问答失败: {str(e)}"
    # 在SilicanAPI类中添加新方法
    def generate_planting_advice(self, crop_type, prompt=None):
        """生成作物种植建议"""
        if prompt is None:
            prompt = f"""请为{crop_type}提供详细的种植计划，包括以下内容：
        1. 播种时间和方法
        2. 施肥时间和肥料类型
        3. 浇水时间和水量要求
        4. 病虫害防治时间和方法
        5. 收获时间和方法
        请按时间顺序列出关键农事活动。"""
    
        headers = {
        "Authorization": f"Bearer {self.api_key}",
        "Content-Type": "application/json"
    }
    
        payload = {
        "model": "Qwen/Qwen2.5-72B-Instruct", 
        "messages": [
            {
                "role": "user",
                "content": prompt
            }
        ],
        "max_tokens": 2000,
        "temperature": 0.7
    }
    
        try:
            response = requests.post(
                f"{self.base_url}/chat/completions", 
                headers=headers, 
                json=payload,
                timeout=60
        )
            response.raise_for_status()
            result = response.json()
            return result["choices"][0]["message"]["content"]
        except Exception as e:
            return f"生成种植建议失败: {str(e)}"

    def extract_events_from_advice(self, advice_text):
        """从建议文本中提取关键事件"""
        prompt = f"""请从以下农业建议中提取关键农事活动事件，并为每个事件标注时间参考和重要性(高/中/低)。
        输出格式要求为JSON列表，每个元素包含:
        - activity: 活动描述
        - time_reference: 时间参考(如:播种后10天, 3月中旬等)
        - importance: 重要性(高/中/低)
    
        农业建议文本:
        {advice_text}
    
        请只返回JSON格式的数据，不要其他内容。"""
    
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
    }
    
        payload = {
            "model": "Qwen/Qwen2.5-72B-Instruct", 
            "messages": [
            {
                "role": "user",
                "content": prompt
            }
        ],
            "max_tokens": 2000,
            "temperature": 0.3 
    }
    
        try:
            response = requests.post(
                f"{self.base_url}/chat/completions", 
                headers=headers, 
                json=payload,
                timeout=60
        )
            response.raise_for_status()
            result = response.json()
        
        # 尝试从响应中提取JSON
            import re
            json_match = re.search(r'\[.*\]', result["choices"][0]["message"]["content"], re.DOTALL)
            if json_match:
                import json
                return json.loads(json_match.group())
            else:
            # 如果无法提取JSON，返回空列表
                return []
            
        except Exception as e:
            print(f"提取事件失败: {str(e)}")
            return []

